import http.client
from sys import platform

import json
from flask import Flask, request, jsonify
from flask_cors import CORS
from matplotlib.pyplot import connect
from tempfile import TemporaryFile
from detect import getDetectResult
import numpy as np
import os

app = Flask(__name__)
CORS(app, resources=r'/*')


@app.route('/')
def hello_world():
    print(type(app))
    return 'Hello World!'


def getPlatform():
    if platform == "linux" or platform == "linux2":
        return "linux"
    elif platform == "darwin":
        return "mac"
    elif platform == "win32":
        return "windows"

def jsonPost(host, mapper, json_data):
    json_bytes = json.dumps(json_data).encode('utf-8')
    conn = http.client.HTTPConnection(host)
    conn.request("POST", mapper, json_bytes, {'Content-type': 'application/json'})
    response = conn.getresponse()
    return response.read().decode('utf-8')


def getResult(file):
    result = {}
    if file is None:
        return result
    if getPlatform() == "windows":
        with TemporaryFile(suffix=os.path.splitext(file.filename)[1], delete=False) as tempFile:
            filename = tempFile.name
            tempFile.write(file.stream.read())
            tempFile.close()
            result = getDetectResult(filename)
            os.remove(filename)
    else:
        with TemporaryFile(suffix=os.path.splitext(file.filename)[1]) as tempFile:
            filename = tempFile.name
            tempFile.write(file.stream.read())
            result = getDetectResult(filename)
    return result


@app.route('/file', methods=['POST'])
def file():
    uploadFile = request.files['file']
    return jsonify(getResult(uploadFile))

bicycleGroup = ["wheelbarrow", "tandem bicycle", "moped", "scooter", "mountain bike", "tricycle", "unicycle",
                "motorcycle", "bicycle"]

@app.route('/fileCount', methods=['POST'])
def fileCount():
    uploadFile = request.files['file']
    threshold = float(request.form['threshold'])
    result = getResult(uploadFile)
    count = 0
    for key, values in result.items():
        if key in bicycleGroup:
            for value in values:
                count += 1 if value > threshold else 0
    jsonPost("353zkxp99595.vicp.fun", "/carport/carportinfo/save", {
        "district": "①号--01",
        "parkingQuantity": count
    })
    return jsonify({"count": count})

if __name__ == '__main__':
    app.run()
